<template>
    <el-table
        ref="tableRef"
        :data="tableData"
        :height="autoHeight ? tableHeight : undefined"
        :highlight-current-row="singleSelect"
        class="base-table"
        :tooltip-options="{
            popperOptions: {
                strategy: 'absolute'
            }
        }"
        v-bind="$attrs"
    >
        <BaseTableColumn
            v-for="(column, columnIndex) in tableColumns"
            :key="column.prop ? column.prop + columnIndex : columnIndex"
            :column="column"
        >
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
                <slot :name="slot" v-bind="scope" />
            </template>
        </BaseTableColumn>
        <template #empty>
            <BaseEmpty :imgSize="35"></BaseEmpty>
        </template>
    </el-table>
</template>

<script setup>
import BaseTableColumn from './BaseTableColumn.vue'
import BaseEmpty from './BaseEmpty.vue'
import { onBeforeUnmount, onMounted, ref, unref, useAttrs, useSlots } from 'vue'

defineOptions({
    name: 'BaseTable',
    inheritAttrs: false
})

const tableRef = ref(null)
const props = defineProps({
    tableColumns: {
        type: Array,
        default: () => []
    },
    tableData: {
        type: Array,
        default: () => []
    },
    paginationData: {
        type: Object,
        default: () => ({
            pageNum: 1,
            pageSize: 10,
            total: 0
        })
    },
    autoHeight: {
        type: Boolean,
        default: true
    },
    singleSelect: {
        type: Boolean,
        default: false
    }
})

const attrs = useAttrs()

const slots = useSlots()

const tableHeight = ref(0)
const initTableHeight = () => {
    const resizeObserver = new ResizeObserver(entries => {
        const { height } = entries.shift()?.contentRect
        tableHeight.value = height
        unref(tableRef).scrollBarRef.update()
    })
    onMounted(() => {
        resizeObserver.observe(unref(tableRef).$el.parentElement)
    })
    onBeforeUnmount(() => {
        resizeObserver.disconnect()
    })
}
props.autoHeight && initTableHeight()

// 单选
const setSingleSelect = row => {
    unref(tableRef).setCurrentRow(row)
}

defineExpose({
    tableRef,
    setSingleSelect
})
</script>

<style lang="scss" scoped>
.base-table {
    --el-table-header-bg-color: #f8f8f9;

    :deep() {
        .el-table__empty-text:has(> .base-empty) {
            line-height: unset;
            width: 100%;
            height: 100%;
        }
    }

}
</style>